package com.ruoyi.file.service.impl;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.file.service.ISysFileService;
import com.ruoyi.file.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Minio 文件存储
 *
 * @author ruoyi
 */
@Service
@Primary
public class ObsSysFileServiceImpl implements ISysFileService {
    @Autowired
    private OBSUtil obsUtil;
    @Autowired
    private IdWorker idWorker;

    /**
     * Minio文件上传接口
     *
     * @param file 上传的文件
     * @return 访问地址
     * @throws Exception obs://fk-file-bucket/temp/2024/04/26/
     */
    @Override
    public String uploadFile(MultipartFile file, String tableName, String colName, String watermark) throws Exception {
        // 1.获取上传的文件原始名称
        String originalFileName = StringUtils.cleanPath(file.getOriginalFilename());

        String fileName = FileUploadUtils.extractFilename(file);
        // 1.1获取拓展名
        String fileExtension = "";
        int dotIndex = fileName.lastIndexOf(".");
        if (dotIndex != -1) {
            fileExtension = fileName.substring(dotIndex + 1).toLowerCase();
        }

        HashMap<String, String> resultMap = new HashMap<>();
        // 2.组合文件名称（例如：企业营业执照_营业执照.pdf）
        String fileStorageName = tableName + "/" + colName + "/" + fileName; // 您可以生成唯一的文件名
        if (com.ruoyi.common.core.utils.StringUtils.isNotEmpty(watermark)) {
            // 按照 | 分割 watermark
            String[] watermarkParts = watermark.split("\\|");
            String descriptionText = watermarkParts[0];
            String addressText ="";

            if(watermarkParts.length>1){
                addressText = watermarkParts[1];
            }


            String gpsText ="";
            if(watermarkParts.length>2){
                gpsText = watermarkParts[2];
            }


            // 3.添加水印
            File watermarkFile = WatermarkUtils.addTextWatermark(file, descriptionText, addressText, gpsText);
            // 4.将File转换为MultipartFile
            MultipartFile multipartFile = MultipartFileConverter.convertFileToMultipartFile(watermarkFile);
            // 5.保存文件到obs
             resultMap = obsUtil.uploadFile(multipartFile, fileStorageName);
            // 删除临时文件
            watermarkFile.delete();
        }else {
            resultMap = obsUtil.uploadFile(file, fileStorageName);
        }


        resultMap.put("fileExtension", fileExtension);
        resultMap.put("fileName", fileName);
        resultMap.put("fileStorageName", fileStorageName);
        resultMap.put("originalFileName", originalFileName);



        return resultMap.toString();
    }


}
